# views.py
import sys
import traceback

from django.core.paginator import Paginator, EmptyPage
from django.db import transaction, connection
from django.db.models import Count, Avg, Q, Max
from django.forms import models
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from user.models import UserToken
from .models import InterviewRecord, Company
from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
from sparkai.core.messages import ChatMessage
import json
from datetime import datetime
from django.core.exceptions import ValidationError
# 新增面试记录
@csrf_exempt
@require_http_methods(["POST"])
def add_interview_record(request):
    response_data = {
        'status': 'error',
        'message': '',
        'record_id': None
    }

    try:
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            response_data['message'] = '未登录'
            return JsonResponse(response_data, status=401)
        # 解析JSON数据
        data = json.loads(request.body)

        # 验证必填字段
        required_fields = ['user_id','company_id']
        for field in required_fields:
            if field not in data or not data[field]:
                response_data['message'] = '缺少必填字段: %s'%field
                return JsonResponse(response_data, status=400)

        # 创建记录对象
        new_record = InterviewRecord(
            user_id=data['user_id'],
            company_id=data['company_id'],
            type = 0
        )

        # 保存到数据库
        new_record.save()

        # 构建成功响应
        response_data.update({
            'status': 'success',
            'message': '记录添加成功',
            'record_id': new_record.id,
            'created_at': new_record.created_at.strftime("%Y-%m-%d %H:%M:%S")
        })
        return JsonResponse(response_data)

    except json.JSONDecodeError:
        response_data['message'] = '无效的JSON格式'
        return JsonResponse(response_data, status=400)
    except UserToken.DoesNotExist:
        response_data['message'] = '用户未授权'
        return JsonResponse(response_data, status=400)
    except Exception as e:
        response_data['message'] = '服务器错误: %s'%str(e)
        return JsonResponse(response_data, status=500)

# 批量预约面试
@csrf_exempt
@require_http_methods(["POST"])
def add_interview_records(request):
    response_data = {
        'status': 'error',
        'message': '',
        'records': []
    }


    # 身份验证
    # auth_header = request.headers.get("Authorization", "")
    # token = UserToken.objects.get(key=auth_header)
    # if not token.user.is_authenticated:
    #     response_data['message'] = '未登录'
    #     return JsonResponse(response_data, status=401)

    # 解析JSON数据
    data = json.loads(request.body)

    # 使用事务保证数据一致性
    with transaction.atomic():
        # 先清空企业的预约数据
        deleted_count, _ = InterviewRecord.objects.filter(company_id=data['company_id']).delete()
        print(deleted_count)
        # 批量创建记录
        records = []
        for user_id in data['user_ids']:
            records.append(
                InterviewRecord(
                    user_id=user_id,
                    company_id=data['company_id'],
                    type=0
                )
            )

        # 批量插入数据库
        created_records = InterviewRecord.objects.bulk_create(records)

        # 构建响应数据
        response_data['status'] = 'success'
        response_data['message'] = '成功添加%s条记录'%len(created_records)
        response_data['records'] = [{
            'record_id': record.id,
            'user_id': record.user_id,
            'created_at': record.created_at.strftime("%Y-%m-%d %H:%M:%S")
        } for record in created_records]

    return JsonResponse(response_data)



# 加载面试题
@csrf_exempt
@require_http_methods(["POST"])
def load(request):
    try:
        response_data = {
            'message': 'ok',
            'received_data': None
        }
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            return JsonResponse({"message":"未登录"}, status=401)
        # 星火认知大模型Spark Max的URL值，其他版本大模型URL值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
        SPARKAI_URL = 'wss://spark-api.xf-yun.com/v3.5/chat'
        # 星火认知大模型调用秘钥信息，请前往讯飞开放平台控制台（https://console.xfyun.cn/services/bm35）查看
        SPARKAI_APP_ID = '55547a91'
        SPARKAI_API_SECRET = 'ZjE0ODk1NTE0YTE4NTZjOWMzOTdkYjY4'
        SPARKAI_API_KEY = 'b3f3bd22a03ad0c4284ade3297ef44f4'
        # 星火认知大模型Spark Max的domain值，其他版本大模型domain值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
        SPARKAI_DOMAIN = 'generalv3.5'

        spark = ChatSparkLLM(
            spark_api_url=SPARKAI_URL,
            spark_app_id=SPARKAI_APP_ID,
            spark_api_key=SPARKAI_API_KEY,
            spark_api_secret=SPARKAI_API_SECRET,
            spark_llm_domain=SPARKAI_DOMAIN,
            streaming=False,
            )

        if request.method == 'POST':
            data = json.loads(request.body)
            # 处理数据
            messages4 = [ChatMessage(
                role="user",
                content='我是一名即将毕业的大学生，想针对%s岗位进行一次模拟面试，从自我介绍开始循序渐进对我进行10次提问，每个问题以#号结尾，只需要问题不需要回答，每个问题格式参考"1. 请简单介绍一下自己。#"' % data["interview_position"]
            )]
            handler = ChunkPrintHandler()
            a = spark.generate([messages4], callbacks=[handler])
            arr = a.generations[0][0].text.split("#")[0:10]
            arr = [s.strip() for s in arr]
            return JsonResponse(response_data)
        return JsonResponse({'message': '服务器加载失败!'}, status=400)
    except UserToken.DoesNotExist:
        response_data['message'] = '用户未授权'
        return JsonResponse(response_data, status=400)
    except Exception as e:
        response_data['message'] = '服务器错误: %s'%str(e)
        return JsonResponse(response_data, status=500)
# 保存单个面试过程
@csrf_exempt
@require_http_methods(["POST"])
def save_wd(request):
    try:
        response_data = {
            'message': 'ok',
            'time_str': None
        }
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            return JsonResponse({"message": "未登录"}, status=401)
        if request.method == 'POST':
            data = json.loads(request.body)
            print(data)
        time_str = data["time_str"]
        f = open("jg/"+time_str+".txt","a",encoding='utf-8')
        f.write(data["wd"]+"\n")
        return JsonResponse(response_data)
    except UserToken.DoesNotExist:
        response_data['message'] = '用户未授权'
        return JsonResponse(response_data, status=400)
    except Exception as e:
        response_data['message'] = '服务器错误: %s'%str(e)
        return JsonResponse(response_data, status=500)
# 分析面试结果
@csrf_exempt
@require_http_methods(["POST"])
def jg(request):
    # 星火认知大模型Spark Max的URL值，其他版本大模型URL值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
    SPARKAI_URL = 'wss://spark-api.xf-yun.com/v3.5/chat'
    # 星火认知大模型调用秘钥信息，请前往讯飞开放平台控制台（https://console.xfyun.cn/services/bm35）查看
    SPARKAI_APP_ID = '55547a91'
    SPARKAI_API_SECRET = 'ZjE0ODk1NTE0YTE4NTZjOWMzOTdkYjY4'
    SPARKAI_API_KEY = 'b3f3bd22a03ad0c4284ade3297ef44f4'
    # 星火认知大模型Spark Max的domain值，其他版本大模型domain值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
    SPARKAI_DOMAIN = 'generalv3.5'

    spark = ChatSparkLLM(
        spark_api_url=SPARKAI_URL,
        spark_app_id=SPARKAI_APP_ID,
        spark_api_key=SPARKAI_API_KEY,
        spark_api_secret=SPARKAI_API_SECRET,
        spark_llm_domain=SPARKAI_DOMAIN,
        streaming=False,
    )
    handler = ChunkPrintHandler()
    try:
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            return JsonResponse({"message": "未登录"}, status=401)
        if request.method == 'POST':
            data = json.loads(request.body)
            print(data)
        time_str = data["time_str"]
        gw = data["interview_position"]
        msg = ""
        with open("jg/"+time_str+".txt","r",encoding='utf-8') as f:
            # msg = "以下是我%s岗位的面试过程，请对我的回答做一个优缺点分析，给出介意，并总结一下我现水平的面试通过率:\n"+f.read()
            # msg = msg % gw
            msg = f.read()+"\n如果是1-100分 首先对以上面试过程打一个总分，再对每个问题的回答进行评价，最后做一个总结。总分用()包裹方便我用代码截取。"
        messages5 = [ChatMessage(
            role="user",
            content=msg
        )]
        a2 = spark.generate([messages5], callbacks=[handler])
        message = a2.generations[0][0].text
        # message = ''.join(message.split())
        message = message.replace("\n", "<br>")
        response_data = {
            'code': '1',
            'message': message
        }
        return JsonResponse(response_data)
    except UserToken.DoesNotExist:
        response_data = {
            'code': '0',
            'message': "用户未授权"
        }
        return JsonResponse(response_data)
    except Exception as e:
        response_data = {
            'code': '0',
            'message': "服务器繁忙，请重试。"
        }
        return JsonResponse(response_data)

# 添加企业信息
@csrf_exempt
@require_http_methods(["POST"])
def add_company(request):
    response_data = {
        'status': 'error',
        'message': '',
        'company_id': None,
        'created_at': None
    }
    try:
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            response_data['message'] = '未登录'
            return JsonResponse(response_data, status=401)
        # 解析JSON数据
        data = json.loads(request.body)

        # 验证必填字段
        required_fields = [
            'name', 'job_title', 'location',
            'salary_min', 'salary_max',
            'start_date', 'end_date',
            'interview_format', 'requirements'
        ]
        for field in required_fields:
            if not data.get(field):
                response_data['message'] = '缺少必填字段: %s'%{field}
                return JsonResponse(response_data, status=400)

        # 验证薪资范围
        if int(data['salary_min']) > int(data['salary_max']):
            response_data['message'] = '最高薪资不能低于最低薪资'
            return JsonResponse(response_data, status=400)

        # 验证面试形式
        valid_interview_formats = [choice[0] for choice in Company.INTERVIEW_FORMAT_CHOICES]
        print(valid_interview_formats)
        if data['interview_format'] not in valid_interview_formats:
            response_data['message'] = '无效的面试形式，可选值: %s'%{", ".join(valid_interview_formats)}
            return JsonResponse(response_data, status=400)

        # 转换日期格式
        try:
            start_date = datetime.strptime(data['start_date'], '%Y-%m-%d').date()
            end_date = datetime.strptime(data['end_date'], '%Y-%m-%d').date()
        except ValueError:
            response_data['message'] = '日期格式无效，请使用YYYY-MM-DD格式'
            return JsonResponse(response_data, status=400)

        # 创建企业记录
        new_company = Company(
            name=data['name'],
            job_title=data['job_title'],
            location=data['location'],
            salary_min=data['salary_min'],
            salary_max=data['salary_max'],
            start_date=start_date,
            end_date=end_date,
            interview_format=data['interview_format'],
            requirements=data['requirements'],
            remarks=data.get('remarks')  # 可选字段
        )

        # 完整模型验证
        new_company.full_clean()

        # 保存到数据库
        new_company.save()

        # 构建成功响应
        response_data.update({
            'status': 'success',
            'message': '企业信息创建成功',
            'company_id': new_company.id,
            'created_at': new_company.created_at.strftime("%Y-%m-%d %H:%M:%S")
        })
        return JsonResponse(response_data)

    except json.JSONDecodeError:
        response_data['message'] = '无效的JSON格式'
        return JsonResponse(response_data, status=400)
    except UserToken.DoesNotExist:
        response_data['message'] = '用户授权未通过'
        return JsonResponse(response_data, status=400)
    except ValidationError as e:
        response_data['message'] = '数据验证失败: '%{", ".join(e.messages)}
        return JsonResponse(response_data, status=400)
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()

        # 提取最后一个堆栈帧（即错误发生的具体位置）
        stack_summary = traceback.extract_tb(exc_traceback)[-1]
        print(stack_summary)
        response_data['message'] = '服务器错误: %s'%{str(e)}
        return JsonResponse(response_data, status=500)

# 根据ID删除企业信息
@csrf_exempt
@require_http_methods(["GET"])
def delete_company(request, company_id):
    """
    根据ID删除企业信息
    请求示例：DELETE /api/companies/1/
    """
    response_data = {
        'status': 'error',
        'message': '',
        'deleted_id': None
    }

    try:
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            response_data['message'] = '未登录'
            return JsonResponse(response_data, status=401)
        # 检查ID有效性
        if not isinstance(company_id, int) or company_id <= 0:
            response_data['message'] = '企业ID必须为正整数'
            return JsonResponse(response_data, status=400)

        # 获取并删除记录
        company = Company.objects.get(id=company_id)
        company.delete()

        # 构建成功响应
        response_data.update({
            'status': 'success',
            'message': '企业 %s 删除成功'%{company.name},
            'deleted_id': company_id
        })
        return JsonResponse(response_data)

    except Company.DoesNotExist:
        response_data['message'] = 'ID为 %s 的企业不存在'%{company_id}
        return JsonResponse(response_data, status=404)
    except UserToken.DoesNotExist:
        response_data['message'] = '用户授权未通过'
        return JsonResponse(response_data, status=400)
    except Exception as e:
        response_data['message'] = '服务器错误: %s'%{str(e)}
        return JsonResponse(response_data, status=500)

# 查询预约列表
@csrf_exempt
@require_http_methods(["GET"])
def query_company0(request):
    """
    根据user_id和company_id查询面试记录
    请求示例：GET /api/interviews/?user_id=123&company_id=456&page=2&page_size=5
    """
    response_data = {
        'status': 'success',
        'count': 0,
        'page': 1,
        'total_pages': 1,
        'results': []
    }

    try:
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            return JsonResponse({"message": "未登录"}, status=401)
        # 解析请求参数
        params = request.GET
        user_id = params.get('user_id')
        page = int(params.get('page', 1))
        page_size = int(params.get('page_size', 10))
        queryset = InterviewRecord.get_student_interviews(user_id)
        paginator = Paginator(queryset, page_size)
        try:
            records_page = paginator.page(page)
        except EmptyPage:
            records_page = paginator.page(paginator.num_pages)
        # 序列化结果
        serialized_data = []

        for company in records_page:
            # 生成文件访问URL

            serialized_data.append({
                "id":company["id"],"user_id":company["user_id"],"company_id":company["company_id"],"name":company["name"],"job_title":company["job_title"],"location":company["location"],"date_range":company["date_range"]
            })
            # 构建响应
            response_data.update({
                'count': paginator.count,
                'page': page,
                'total_pages': paginator.num_pages,
                'results': serialized_data
            })

        return JsonResponse(response_data)
    except ValueError as ve:
        return JsonResponse({'status': 'error', 'message': str(ve)}, status=400)
    except InterviewRecord.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '未找到相关记录'}, status=404)
    except UserToken.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '用户授权未通过'}, status=400)
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': '服务器错误: %s'}%{str(e)}, status=500)

# 保存面试记录
@csrf_exempt
@require_http_methods(["POST"])
def update_interview_record(request, record_id):
    response_data = {
        'status': 'success',
        'updated_fields': [],
        'errors': []
    }

    try:
        auth_header = request.headers.get("Authorization", "")
        token = UserToken.objects.get(key=auth_header)
        if not token.user.is_authenticated:
            return JsonResponse({"message": "未登录"}, status=401)
        # 获取目标记录
        record = InterviewRecord.objects.get(id=record_id)

        # 解析请求数据
        update_data = json.loads(request.body)
        update_data["type"]=1
        # 执行字段级更新
        for field, value in update_data.items():
            # 跳过不可修改字段
            if field in ['id', 'created_at', 'user_id', 'company_id']:
                response_data['errors'].append("禁止修改字段: %s"%{field})
                continue

            # 验证字段存在性
            if not hasattr(record, field):
                response_data['errors'].append("无效字段: %s"%{field})
                continue
            # 执行更新
            setattr(record, field, value)
            response_data['updated_fields'].append(field)

        # 批量保存更新
        if not response_data['errors']:
            record.save()
            return JsonResponse(response_data)
        else:
            return JsonResponse(response_data, status=400)

    except InterviewRecord.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '记录不存在'}, status=404)
    except json.JSONDecodeError:
        return JsonResponse({'status': 'error', 'message': '无效的JSON格式'}, status=400)
    except UserToken.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '用户授权未通过'}, status=400)
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()

        # 提取最后一个堆栈帧（即错误发生的具体位置）
        stack_summary = traceback.extract_tb(exc_traceback)[-1]
        print(stack_summary)
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

# 查询企业列表
@csrf_exempt
def interview_list(request):
    # 获取分页参数并设置默认值
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', 10))

    # 获取排序后的查询集（按创建时间倒序）
    companys = Company.objects.all().order_by('-created_at')

    # 初始化分页器
    paginator = Paginator(companys, page_size)

    try:
        current_page = paginator.page(page)
    except EmptyPage:
        # 如果页码超出范围，返回最后一页
        current_page = paginator.page(paginator.num_pages)

    # 序列化数据
    serialized_companys = []
    for company in current_page:
        serialized_companys.append({
            'id':company.id,
            'name': company.name,
            'job_title': company.job_title,
            'location': company.location,
            'created_at': company.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'salary': company.salary_range,
            'is_active': company.is_active,
            'date_range':company.date_range,
            'interview_format': company.interview_format,  # 获取选项显示值
            'requirements': company.requirements,
            'remarks': company.remarks,
            'word_path': company.word_path
        })

    # 构造响应数据
    response_data = {
        'status': 'success',
        'count': paginator.count,
        'page': current_page.number,
        'total_pages': paginator.num_pages,
        'results': serialized_companys
    }
    print(response_data)
    return JsonResponse(response_data)

@csrf_exempt
def get_interview_stats(request):
    params = request.GET
    user_id = params.get('user_id')
    # 基本统计聚合查询（一次数据库查询完成三个指标）
    stats = InterviewRecord.objects.filter(user_id=user_id).aggregate(
        interviewed_count=Count('id', filter=Q(type=1)),
        pending_count=Count('id', filter=Q(type=0)),
        avg_score=Avg('total_score', filter=Q(type=1))
    )

    # 处理空值情况
    interviewed_count = stats['interviewed_count'] or 0
    pending_count = stats['pending_count'] or 0
    avg_score = round(stats['avg_score'], 2) if stats['avg_score'] is not None else 0

    # 获取历史分数变化（单独查询排序记录）
    score_history = InterviewRecord.objects.filter(
        user_id=user_id,
        type=1,
        total_score__isnull=False  # 排除无成绩记录
    ).order_by('created_at').values_list('total_score', 'created_at')

    # 构建时间序列数据
    history_data = [{
        "score": score,
        "date": date.strftime("%Y-%m-%d %H:%M")  # 格式化时间
    } for score, date in score_history]

    return JsonResponse({
        "interviewed_count": interviewed_count,
        "pending_count": pending_count,
        "avg_score": avg_score,
        "score_history": history_data
    })

@csrf_exempt
def interview_stats_history(request):
    params = request.GET
    user_id = params.get('user_id')
    # 聚合查询获取核心统计指标
    stats = InterviewRecord.objects.filter(user_id=user_id).aggregate(
        total_interviews=Count('id', filter=Q(type=1)),
        scored_count=Count('id', filter=Q(type=1, total_score__isnull=False)),
        passed_count=Count('id', filter=Q(type=1, total_score__gte=60)),
        avg_score=Avg('total_score', filter=Q(type=1, total_score__isnull=False)),
        max_score=Max('total_score', filter=Q(type=1, total_score__isnull=False)),
    )

    # 处理统计结果
    total_interviews = stats['total_interviews'] or 0
    scored_count = stats['scored_count'] or 0
    passed_count = stats['passed_count'] or 0

    avg_score = round(stats['avg_score'], 2) if stats['avg_score'] else 0
    max_score = stats['max_score'] if stats['max_score'] else 0
    pass_rate = round(passed_count / scored_count * 100, 2) if scored_count else 0

    # 获取完整历史记录
    r = get_interview_info_by_user(user_id)
    # 构建结构化响应数据
    return JsonResponse({
        'stats': {
            'total_interviews': total_interviews,
            'pass_rate': pass_rate,
            'average_score': avg_score,
            'highest_score': max_score,
            'scored_interviews': scored_count,
        },
        'history': r
    })

def get_interview_info_by_user(user_id):
    query = """
        SELECT
            ir.user_id,
            ir.company_id,
            ir.total_score,
            ir.created_at,
            ir.remarks,
            c.name,
            c.job_title,
            c.interview_format
        FROM
            interview_record AS ir
        INNER JOIN
            company AS c
        ON
            ir.company_id = c.id
        WHERE
            ir.user_id = %s and ir.type = 1
    """
    with connection.cursor() as cursor:
        cursor.execute(query, [user_id])
        columns = [col[0] for col in cursor.description]
        results = [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]
    return results
#面试结果保存
@csrf_exempt
def update_interview_files(request):
    # 获取参数
    data = json.loads(request.body)
    record_id = data['id']
    evaluation_file = data['evaluation_file_path']
    process_file = data['interview_process_file_path']
    video_file = data['video_path']

    # 参数校验
    if not all([record_id, evaluation_file, process_file, video_file]):
        return JsonResponse({"error": "缺少必要参数"}, status=400)

    try:
        # 获取记录对象
        record = get_object_or_404(InterviewRecord, pk=record_id)

        # 更新字段
        record.evaluation_file_path = evaluation_file
        record.interview_process_file_path = process_file
        record.video_path = video_file
        record.type = '1'

        # 触发 save() 保存单个对象
        record.save(update_fields=[
            'evaluation_file_path',
            'interview_process_file_path',
            'video_path',
            'type'
        ])

        return JsonResponse({
            "message": "更新成功",
            "data": {
                "id": record.id,
                "evaluation_file": record.evaluation_file_path,
                "process_file": record.interview_process_file_path,
                "video": record.video_path
            }
        })

    except Exception as e:
        print(e)
        return JsonResponse({"error": "更新失败"}, status=500)
